<template>
  <div class="cart">
    <!-- 标题 -->
    <div class="sticky-nav">
    <van-nav-bar :left-arrow="data.cartList.length === 0 ? false : true"
                 @click-left="onClickLeft"
                 :right-text="data.cartList.length === 0 ? '' : '编辑'"
                 style="padding: 0 16px;background-color: white"
                 title="购物车" >
      <template #left>
        <img src="@/assets/images/icon/icon_left.png" alt="返回" style="width: 45px; height: 45px;">
      </template>
      <template #right>
        <div v-if="isEditing" style="color: rgb(0, 0, 0); font-size: 16px;" @click="toggleEdit">编辑</div>
        <div v-else="isEditing" style="color: rgb(0, 0, 0); font-size: 16px;" @click="toggleEdit">完成</div>
      </template>
    </van-nav-bar>
    </div>
    <!-- 空购物车状态 -->
    <div v-if="isLoading">正在加载购物车...</div>
    <div v-else-if="data.cartList.length === 0" class="empty-cart">
      <p>购物车是空的</p>
    </div>

    <!-- 购物车商品列表 -->
    <div v-else>
      <van-checkbox-group v-model="selectedIds" @change="handleCheckboxChange">
        <div class="cart-item card" v-for="item in data.cartList" :key="item.id">
          <van-checkbox  :name="item.id" @click="CheckboxClick(item)" />
          <van-card
              :num="item.shangpinxiangqingShuliang"
              :price="parseInt(item.shangpinxiangqingJiage).toFixed(2)"
              :desc="item.shangpinxiangqingFenlei"
              :title="item.shangpinxiangqingName"
              :thumb="item.shangpinxiangqingImg"
          >
            <template #footer>
              <van-stepper v-model="item.goumaishuliang"  button-size="22" @change="updateGoumaishuliang(item)"/>
            </template>
          </van-card>
        </div>
      </van-checkbox-group>
    </div>


    <van-submit-bar
        :price="totalPrice * 100"
        button-text="提交订单"
        @submit="onSubmit"
        v-if="isEditing"
    >
          <van-checkbox v-model:checked="isAllChecked" @click="toggleAll">全选</van-checkbox>
      <!-- tip 插槽 -->
      <template #tip>
        你的收货地址不支持配送, <span @click="onClickLink">修改地址</span>
      </template>
    </van-submit-bar>

    <!-- 自定义底部结算栏 -->
    <van-submit-bar
    :price="totalPrice * 100"
    button-text="结算"
    @submit="onSubmit"
    v-if="isEditing"
    >
      <van-checkbox v-model:checked="isAllChecked" @click="toggleAll">全选</van-checkbox>
    </van-submit-bar>
    <van-submit-bar v-else style="justify-items: flex-start;">
      <template #default style="margin-left: 0">
        <van-checkbox v-model:checked="isAllChecked" @click="toggleAll">全选</van-checkbox>
      </template>
      <template #button>
        <van-button class="boot" style="margin-left: 90px;" type="danger" size="small" @click="shoucang">移入收藏</van-button>
        <van-button class="boot" style="margin-left: 20px;border-radius: 15.3333px;min-width: 90px;" type="danger" size="small" @click="onDelete">删除</van-button>
      </template>
    </van-submit-bar>

  </div>
</template>
<script setup>
import {ref, computed, reactive} from 'vue'
import {CheckboxGroup as VanCheckboxGroup, showNotify} from 'vant'
import { Checkbox as VanCheckbox } from 'vant'
import { Card as VanCard } from 'vant'
import { Stepper as VanStepper } from 'vant'
import { SubmitBar as VanSubmitBar } from 'vant'
import router from "@/router/index.js";
import request from "@/utils/request.js";
import { showToast } from 'vant';
import { showConfirmDialog } from 'vant';
import Router from "@/router/index.js";
const data = reactive({
  cartList: [],
  user: JSON.parse(localStorage.getItem('code_user') || '{}'),
})
const isEditing = ref(true)
const isLoading = ref(true)
// 当前选中的商品 ID 列表
const selectedIds = ref([]);
// 收藏按钮
const shoucang = () => {
  showConfirmDialog({
    message:
        '按钮功能暂未实现，请谅解。',
  }).then(() => {})
  .catch(() => {})

}
const onClickLeft = () => {
  // 方式一：返回上一页
  router.back()

  // 方式二：跳转到指定页面，例如分类页
  // router.push('/category')
}
// 编辑按钮逻辑
const toggleEdit = () => {
  isEditing.value = !isEditing.value
}

const handleCheckboxChange = (value) => {
  selectedIds.value = value;
}

const CheckboxClick = (item) => {
  request.put('gouwuche/update', {
    id: item.id,
    shangpinId: item.shangpinId,
    userId: item.userId,
    goumaishuliang: item.goumaishuliang,
    zhuangtai: item.zhuangtai === "1" ? "0" : "1"
  }).then(res => {
    if (res.code === '200') {
      showToast('修改成功');
      loadCartList()
    }
  })
}
const loadCartList = () => {
  if (data.user.id) {
    if (data.user.id) {
      request.get('gouwuche/selectAll', {
        params: {
          userId: data.user.id
        }
      }).then(res => {
        data.cartList = res.data || []
        data.cartList.map(item =>{
          if(item.zhuangtai === "1"){
            if(!selectedIds.value.includes(item.id)){
              selectedIds.value.push(item.id)
            }
          }
        } );
        // console.log(data.cartList);
      }).catch(err => {
        showNotify({ type: 'danger', message: err });
      }).finally(() => {
        isLoading.value = false
      })
    }
  }else {
    isLoading.value = false
  }

}
loadCartList()

// 是否全选
const isAllChecked = computed(() => selectedIds.value.length === data.cartList.length)

// 总价计算
const totalPrice = computed(() => {
  return data.cartList
      .filter(item => selectedIds.value.includes(item.id))
      .reduce((sum, item) => sum + item.shangpinxiangqingJiage * item.goumaishuliang, 0)
})

// 全选/取消全选
const toggleAll = () => {
  if (isAllChecked.value) {
    selectedIds.value = []
  } else {
    selectedIds.value = data.cartList.map(item => item.id)
  }
}

// 提交结算
const onSubmit = () => {
  if (selectedIds.value.length === 0) {
    showToast('请至少选择一件商品');
    return
  }
  // 这里可以跳转到订单页或弹出确认框
  // console.log('结算:', selectedIds.value)
  Router.push('/checkout');
  // showToast('结算成功');
}
const onClickLink = () => {
  // router.push('/address')
  console.log('跳转到地址页');
}
// 删除选中商品
const onDelete = () => {
  if (selectedIds.value.length === 0) {
    showToast('请至少选择一件商品');
    return;
  }

  showConfirmDialog({
    message:
        '你确定要删除你选中的商品吗？',
  })
      .then(() => {
        // on confirm
        // 这里可以调用接口删除商品
        // console.log('删除以下商品:', selectedIds);
        selectedIds.value.filter(item => {
          request.delete('gouwuche/delete/' + item).then(res => {
            if (res.code === '200') {
              showToast('删除成功');
              loadCartList()
            }
          })
        });
      })
      .catch(() => {
        // on cancel
      });
};
const updateGoumaishuliang = (item) => {
  request.put('gouwuche/update', {
    id: item.id,
    shangpinId: item.shangpinId,
    userId: item.userId,
    goumaishuliang: item.goumaishuliang,
    zhuangtai: item.zhuangtai
  }).then(res => {
    if (res.code === '200') {
      showToast('修改成功');
      loadCartList()
    }
  })
}
</script>
<style scoped>
.sticky-nav {
  position: sticky;
  top: 0;
  z-index: 999; /* 确保在其他内容之上 */
  background-color: white; /* 避免透明背景影响视觉效果 */
}
.boot{
  border-radius: 15.3333px;
  color: rgba(0, 0, 0, 0.5);
  background-color: white;
  border-color: rgba(0, 0, 0, 0.3);
  min-width: 90px;
  border-width: 1px;
}
.custom-checkout-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  background-color: #fff;
  padding: 12px 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
  z-index: 999;
  height: 96.15375px;
}

.left-section {
  flex: 1;
}

.right-section {
  text-align: right;
}

.total-price {
  font-size: 14px;
  margin-bottom: 4px;
}

.checkout-button {
  background-color: #ee0a24;
  color: white;
  border: none;
  padding: 8px 16px;
  font-size: 16px;
  border-radius: 4px;
  cursor: pointer;
}

.checkout-button.disabled {
  background-color: #ccc;
  cursor: not-allowed;
}
.cart {
  height: 100vh;
  padding-bottom: 50px;
  background-color: #f7f8fa;
}

.empty-cart {
  text-align: center;
  margin-top: 100px;
  color: #666;
}

.cart-item {
  display: flex;
  align-items: center;
  justify-content: center;
  border-bottom: 1px solid #eee;
  padding: 10px;
  border-radius: 8.6px;
  width: 90%;
  margin: 10px auto;
  width: 90%;
  margin: 10px auto;
}
.van-card {
  background-color: white;
}

.van-checkbox {
  margin-right: 10px;
}

.van-card__footer {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}
.van-nav-bar .van-icon {
  color: #ff5000; /* 修改颜色 */
  font-size: 24px; /* 修改大小 */
}


</style>

